package edu.biwu.utils;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private JDBCUtils() {
    }

    //创建一个连接池
    private static BasicDataSource bs;

    static {
        Properties properties = new Properties();
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);


            bs=new BasicDataSource();
            //设置连接池参数
            bs.setDriverClassName(properties.getProperty("driver"));
            bs.setUrl(properties.getProperty("url"));
            bs.setUsername(properties.getProperty("user"));
            bs.setPassword(properties.getProperty("password"));

            //设置可选参数
            bs.setInitialSize(12);
            bs.setMaxTotal(12);
            bs.setMaxIdle(2);
            bs.setMinIdle(1);
            bs.setMaxWaitMillis(30000);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getCollection(){
        Connection con=null;
        try {
            con = bs.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;

    }

    public static DataSource getDataSource(){
        return bs;
    }

    public static void release(Connection con, Statement statement, ResultSet rs){
        if (con==null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
